Skip to main content

constructor 判断类型的原理

原理:每一个对象实例都可以通过 constrcutor 对象访问它的构造函数

注不能用于 undefined 与 null 因为它们没有构造函数

console.log('abc'.constructor)
String() { [native code] }

console.log([].constructor)
Array() { [native code] }

正则替换:展示类型名称

var a = new Array()
alert(a.constructor.toString().match(/^function ([^(]*)/)[1]) // Array

参考文章:javascript 中判断数据类型(constructor) – PHPor 的 Blog